package com.cy.pj.ws;

import com.cy.pj.pojo.Message;
import com.cy.pj.utils.MessageUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpSession;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint(value = "/chat",configurator = GetHttpSessionConfigurator.class)
@Component
public class ChatEndPoint {
    //用来存储每一个客户端对象对应的ChatEndpoint
    private static Map<String,ChatEndPoint> onLineUsers = new ConcurrentHashMap<>();
    //声明Session对象，通过该对象可以发送给指定用户
    private Session session;
    //声明一个HttpSession对象，之前存储了用户名
    private HttpSession httpSession;
    @OnOpen
    public void onOpen(Session session, EndpointConfig config){
        //将局部session赋值给成员session
        this.session = session;
        //获取httpsession对象
        HttpSession httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
        this.httpSession = httpSession;
        //从httpsession中获取用户名
        String username = (String) httpSession.getAttribute("user");
        //将当前对象存储到容器中
        onLineUsers.put(username,this);
        //将当前在线用户推送给所有客户端
        //1.获取消息
        String message = MessageUtils.getMessage(true,null,getNames());
        //2.调用该方法进行系统消息推送
        broadcastAllUsers(message);
    }
    private void broadcastAllUsers(String message){
        //要将该消息推送给所有客户端
        try{
            Set<String> names = onLineUsers.keySet();
            for(String name : names){
                ChatEndPoint chatEndPoint = onLineUsers.get(name);
                chatEndPoint.session.getBasicRemote().sendText(message);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private Set<String> getNames(){
        return onLineUsers.keySet();
    }
    @OnMessage
    public void onMessage(String message,Session session){
        try{
            ObjectMapper mapper = new ObjectMapper();
            Message mess = mapper.readValue(message,Message.class);
            //获取要将数据发送给的用户
            String toName = mess.getToName();
            //获取消息数据
            String data = mess.getMessage();
            //获取当前登录的用户
            String username = (String) httpSession.getAttribute("user");
            //获取推送给指定用户消息格式的数据
            String resultMessage = MessageUtils.getMessage(false,username,data);
            //发送消息
            onLineUsers.get(toName).session.getBasicRemote().sendText(resultMessage);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    @OnClose
    public void onClose(Session session){
        String username = (String) httpSession.getAttribute("user");
        onLineUsers.remove(username);
        MessageUtils.getMessage(true,null,getNames());
    }
}
